<?php

namespace App\Admin\Controllers;

use App\Models\Category;
use App\Models\Product;
use App\Models\Tag;
use Encore\Admin\Form;
use Encore\Admin\Http\Controllers\AdminController;
use Encore\Admin\Table;

class ProductsController extends AdminController
{
    protected $title = '商品列表';

    protected function table()
    {
        $table = new Table(new Product());

        $table->fixColumns(6, 2);
        $table->column('id', __('ID'));
        $table->column('category.name', __('所属分类'));
        $table->column('type', __('类型'))->display(function ($value) {
            return Product::$typeMap[$value];
        })->label([
            Product::TYPE_SINGLE => 'primary',
            Product::TYPE_BOX    => 'success',
        ]);
        $table->column('image', __('商品图片'))->image('', 50);
        $table->column('product_name', __('商品名称'));
        $table->column('brand', __('品牌'));
        $table->column('packaging_information', __('包装信息'));
        $table->column('shelf_life', __('保质期'));
        $table->column('ingredient', __('成分'));
        $table->column('place_of_origin', __('原产地'));
        $table->column('created_at', __('创建时间'));

        // 筛选
        $table->filter(function(Table\Filter $filter){
            $filter->equal('category_id', '所属分类')->select(Category::query()->pluck('name', 'id'));
            $filter->equal('type', '类型')->radio(Product::$typeMap);
            $filter->like('product_name', '商品名称');
        });

        return $table;
    }

    protected function form()
    {
        $form = new Form(new Product());

        $form->select('category_id', __('所属分类'))->options(Category::query()->pluck('name', 'id'))->rules('required');

        $form->image('image', __('商品图片'))->help('建议图片尺寸：280px * 410px')->rules('required|image');

        $form->radio('type', __('类型'))->options(Product::$typeMap)
            // 单个
            ->when(Product::TYPE_SINGLE, function (Form $form) {
                $form->text('title', __('商品标题'))->rules('required');
                $form->image('barcode_image', __('条码图片'))->help('建议图片尺寸：240px * 600px')->rules('image');
                $form->multipleSelect('productTags', '商品标签')->options(Tag::all()->pluck('name', 'id'));

                // 礼盒
            })->when(Product::TYPE_BOX, function (Form $form) {

            })->rules('required');

        $form->text('product_name', __('商品名称'))->rules('required');
        $form->text('brand', __('品牌'))->rules('required');
        $form->text('packaging_information', __('包装信息'))->rules('required');
        $form->text('shelf_life', __('保质期'))->rules('required');
        $form->text('ingredient', __('成分'))->rules('required');
        $form->text('place_of_origin', __('原产地'))->rules('required');

        return $form;
    }
}
